<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医生工作台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .prescription-list { list-style-type: none; padding-left: 0; }
        .prescription-list li { background-color: #f8f9fa; border: 1px solid #dee2e6; margin-bottom: 5px; padding: 5px 10px; border-radius: .25rem; }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">医院管理系统</a>
            <span class="navbar-text">欢迎, {{ doctor.name }} 医生</span>
            <a href="/" class="btn btn-sm btn-outline-light ms-auto">退出登录</a>
        </div>
    </nav>

    <main class="container mt-4">
        <div class="row">
            <!-- 左侧：个人信息 -->
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header"><h4>个人信息</h4></div>
                    <div class="card-body">
                        <p><strong>工号:</strong> {{ doctor.id }}</p>
                        <p><strong>姓名:</strong> {{ doctor.name }}</p>
                        <p><strong>科室:</strong> {{ doctor.department.name }}</p>
                        <p><strong>职称:</strong> {{ doctor.title }}</p>
                    </div>
                </div>
            </div>

            <!-- 右侧：工作区 -->
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header"><h4>我的挂号列表</h4></div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>预约ID</th>
                                        <th>病人姓名</th>
                                        <th>挂号时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="appointments-table-body">
                                    <!-- JS动态填充 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 模态框：用于开具处方 -->
    <div class="modal fade" id="prescriptionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">为 <span id="patientNameForModal"></span> 开具处方</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <h6>已有处方:</h6>
                    <ul id="existingPrescriptions" class="prescription-list mb-3"></ul>
                    <hr>
                    <h6>新增处方项目:</h6>
                    <form id="addPrescriptionForm">
                        <input type="hidden" id="appointmentIdForModal">
                        <div class="mb-3">
                            <label for="itemName" class="form-label">药品/项目名称</label>
                            <input type="text" class="form-control" id="itemName" required>
                        </div>
                        <div class="mb-3">
                            <label for="itemDetails" class="form-label">用法用量/备注</label>
                            <textarea class="form-control" id="itemDetails" rows="2" required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">添加项目</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 从HTML中获取医生ID
        const DOCTOR_ID = "{{ doctor.id }}";

        document.addEventListener('DOMContentLoaded', () => {
            loadAppointments();

            // 绑定表单提交事件
            document.getElementById('addPrescriptionForm').addEventListener('submit', handleAddPrescription);
        });

        // 加载医生的预约列表
        async function loadAppointments() {
            try {
                const response = await fetch(`/api/appointments/doctor/${DOCTOR_ID}`);
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('API 请求失败:', response.status, response.statusText, errorText);
                    throw new Error('网络错误或API返回错误');
                }
                const appointments = await response.json();

                console.log("医生预约数据:", appointments); // 添加日志

                const tableBody = document.getElementById('appointments-table-body');
                if (!tableBody) {
                    console.error("找不到 tbody 元素: appointments-table-body"); // 添加日志
                    return; // 如果找不到元素，直接返回，避免错误
                }

                if (appointments.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="5" class="text-center">暂无挂号记录</td></tr>';
                    return;
                }

                tableBody.innerHTML = appointments.map(appt => {
                    // 确保 prescriptions 是一个数组，即使它是 null 或 undefined
                    const safePrescriptions = appt.prescriptions || [];
                    return `
                        <tr>
                            <td>${appt.id}</td>
                            <td>${appt.patient.name}</td>
                            <td>${appt.appointment_date}</td>
                            <td>
                                <span class="badge ${appt.status === '已就诊' ? 'bg-success' : 'bg-warning'}">
                                    ${appt.status}
                                </span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-info" 
                                        data-prescriptions-json="${encodeURIComponent(JSON.stringify(safePrescriptions))}"
                                        onclick="openPrescriptionModal(${appt.id}, '${appt.patient.name}', this)">
                                    开具处方
                                </button>
                                ${appt.status !== '已就诊' ? `<button class="btn btn-sm btn-success ms-1" onclick="completeAppointment(${appt.id})">完成就诊</button>` : ''}
                            </td>
                        </tr>
                    `;
                }).join('');
            } catch (error) {
                console.error('加载预约列表失败:', error);
                alert('加载预约列表失败');
            }
        }

        // 打开处方模态框
        function openPrescriptionModal(appointmentId, patientName, buttonElement) {
            const prescriptionsJsonEncoded = buttonElement.dataset.prescriptionsJson; // 从 data 属性获取编码后的 JSON 字符串
            const prescriptions = JSON.parse(decodeURIComponent(prescriptionsJsonEncoded)); // 解码并解析

            document.getElementById('appointmentIdForModal').value = appointmentId;
            document.getElementById('patientNameForModal').textContent = patientName;

            const existingList = document.getElementById('existingPrescriptions');
            existingList.innerHTML = prescriptions.length > 0
                ? prescriptions.map(p => `<li><strong>${p.item_name}:</strong> ${p.details}</li>`).join('')
                : '<li>暂无处方</li>';

            const modal = new bootstrap.Modal(document.getElementById('prescriptionModal'));
            modal.show();
        }

        // 提交新处方项目
        async function handleAddPrescription(e) {
            e.preventDefault();
            const appointmentId = document.getElementById('appointmentIdForModal').value;
            const data = {
                appointment_id: parseInt(appointmentId),
                item_name: document.getElementById('itemName').value,
                details: document.getElementById('itemDetails').value,
            };

            const response = await fetch('/api/prescriptions/', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });

            if (response.ok) {
                alert('处方项目添加成功！');
                document.getElementById('addPrescriptionForm').reset();
                // 成功后，可以考虑动态更新模态框内的已有处方列表，或者直接关闭模态框并刷新主列表
                bootstrap.Modal.getInstance(document.getElementById('prescriptionModal')).hide();
                loadAppointments(); // 重新加载主列表以更新数据
            } else {
                alert('添加失败，请重试');
            }
        }

        // 完成就诊
        async function completeAppointment(appointmentId) {
            if (!confirm('确认将此预约标记为"已就诊"吗？')) return;

            const response = await fetch(`/api/appointments/${appointmentId}/complete`, { method: 'PUT' });
            if (response.ok) {
                alert('操作成功！');
                loadAppointments(); // 刷新列表
            } else {
                alert('操作失败，请重试');
            }
        }
    </script>
</body>
</html>